package top.carrotguo.weibo.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {

    //标记当前是否向上滑
    private boolean isSlidingUp = false;

    @Override
    public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
        if (newState == RecyclerView.SCROLL_STATE_IDLE && isSlidingUp) {
            //滑动状态停止并且是上滑，才有可能是加载更多的状态
            //获取最后一个完整可见的item
            int lastItem = manager.findLastCompletelyVisibleItemPosition();
            //获取recycler全部的item个数（包括不在屏幕内的）
            int totalCount = manager.getItemCount();
            if (lastItem == totalCount-1) {
                //加载更多
                onLoadMore();
            }
        }
    }

    @Override
    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        if (dy > 0) {
            isSlidingUp = true;
        } else {
            isSlidingUp = false;
        }
    }

    public abstract void onLoadMore();
}
